package com.blockmeta.bbs.businesslibrary.util;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.net.callback.MyStringCallback;
import com.blockmeta.bbs.baselibrary.net.callback.SuccessCallBack;
import com.blockmeta.bbs.baselibrary.provider.IMApplicationContextProvider;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.gson.GsonUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.constant.NetConstant;
import com.blockmeta.bbs.businesslibrary.dialog.RxDialogEditSureCancel;
import com.blockmeta.bbs.businesslibrary.eventbus.MsgSuccess;
import com.blockmeta.bbs.businesslibrary.flutter.MethodChannelFlutterPlugins;
import com.blockmeta.bbs.businesslibrary.net.callback.ApiStringCallBack;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.pojo.UserPhonePOJO;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.UUID;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.RequestBody;


/**
 * jwt使用过程，在调用init前判断登录态进行refreshjwt，refresh成功进入下一步init，失败则清空登录态，再调init
 * 在正常使用中如果jwt失效会触发401，客户端进行refreshjwt，成功最好能进行前次失败的请求，失败则清空用户态。
 */
public class AccountHelper {
    private static UserPhonePOJO mUserPhonePOJO;
    private static final String KEY_USER_PHONE_INFO = "KEY_USER_PHONE_INFO";

    public static String getUid() {
        if (isLogin()) {
            return String.valueOf(getUserPhonePOJO().getUid());
        }
        return null;
    }

    public static String getToken() {
        if (isLogin()) {
            return getUserPhonePOJO().getToken();
        }
        return "";
    }

    public static int getUidInt() {
        try {
            return getUserPhonePOJO().getUid();
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 判断是否登陆,加上了token判断，防止在特殊情况下token为空但是用户处于登录状态的异常
     *
     * @return
     */
    public static boolean isLogin() {
        return getUserPhonePOJO() != null && !TextUtils.isEmpty(getUserPhonePOJO().getToken());
    }

    public static UserPhonePOJO getUserPhonePOJO() {
        if (mUserPhonePOJO == null) {
            String json = SharedPreferenceUtil.getString(BaseApp.getApp(), KEY_USER_PHONE_INFO, "");
            if (!TextUtils.isEmpty(json)) {
                mUserPhonePOJO = GsonUtil.buildGson().fromJson(json, UserPhonePOJO.class);
                //为了以前单独保存的token做一下兼容
                if (TextUtils.isEmpty(mUserPhonePOJO.getToken())) {
                    mUserPhonePOJO.setToken(SharedPreferenceUtil.getString(BaseApp.getApp(), Constant.GATE_TOKEN, null));
                }
            }
        }
        return mUserPhonePOJO;
    }


    /**
     * 统一了userphone和userserver的获取，避免存在中间状态
     *
     * @param userPhonePOJO
     * @param successCallBack
     */
    public static void setUserPhonePOJOAndGetUserServer(UserPhonePOJO userPhonePOJO, final SuccessCallBack successCallBack) {
        if (userPhonePOJO != null) {
            // 持久化UserInfo
            SharedPreferenceUtil.putString(BaseApp.getApp(), KEY_USER_PHONE_INFO, new Gson().toJson(userPhonePOJO));
            SharedPreferenceUtil.putString(BaseApp.getApp(), Constant.GATE_TOKEN, userPhonePOJO.getToken());
            mUserPhonePOJO = userPhonePOJO;
            if (successCallBack != null) {
                successCallBack.successcallback();
            }
            MethodChannelFlutterPlugins.send("login", new Gson().toJson(userPhonePOJO));
        }
    }

    public static void setUserPhonePOJO(UserPhonePOJO userPhonePOJO) {
        if (userPhonePOJO != null) {
            SharedPreferenceUtil.putString(BaseApp.getApp(), KEY_USER_PHONE_INFO, new Gson().toJson(userPhonePOJO));
            mUserPhonePOJO = userPhonePOJO;
            if (TextUtils.isEmpty(mUserPhonePOJO.getToken())) {
                mUserPhonePOJO.setToken(SharedPreferenceUtil.getString(BaseApp.getApp(), Constant.GATE_TOKEN, null));
            }
            MethodChannelFlutterPlugins.send("login", new Gson().toJson(userPhonePOJO));
        }
    }


    /**
     * 统一登录操作
     *
     * @param userPhonePOJO
     */
    public static void doLogin(UserPhonePOJO userPhonePOJO) {
        setUserPhonePOJOAndGetUserServer(userPhonePOJO, new SuccessCallBack() {
            @Override
            public void successcallback() {

                //登陆成功请求网络数据，Socket连接建立
                //绑定IM 广播和服务
                LogUtils.d("author" + " LoginUI(MsgSuccess message)");
                IMApplicationContextProvider provider = RouterHelper.getProvider(RouterPath.IM_APPLICATIONCONTEXT_PROVIDER);
                if (provider != null) {
                    provider.onCreate(BaseApp.getApp());
                }
                EventBus.getDefault().postSticky(new MsgSuccess("LOGIN"));
            }
        });

        // 重置请求客户端 重新配置参数
        RetrofitFactory.invalidateRetrofitClient();
    }


    /**
     * 退出登录，并且清空Cookie和UserInfo
     */
    public static void doLoginOut() {
        SharedPreferenceUtil.putString(BaseApp.getApp(), KEY_USER_PHONE_INFO, "");
        SharedPreferenceUtil.putString(BaseApp.getApp(), Constant.GATE_TOKEN, "");
        mUserPhonePOJO = null;

        //绑定IM 广播和服务
        LogUtils.d("author" + " LoginUI(loginout message)");
        IMApplicationContextProvider provider = RouterHelper.getProvider(RouterPath.IM_APPLICATIONCONTEXT_PROVIDER);
        if(provider != null){
            provider.onDestroy(BaseApp.getApp());
        }

        MethodChannelFlutterPlugins.send("loginout", "");
    }


    private static String sID = null;
    private static final String INSTALLATION = "INSTALLATION";

    public synchronized static String id(Context context) {
        if (sID == null) {
            File installation = new File(context.getFilesDir(), INSTALLATION);
            try {
                if (!installation.exists())
                    writeInstallationFile(installation);
                sID = readInstallationFile(installation);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return sID;
    }

    private static String readInstallationFile(File installation) throws IOException {
        RandomAccessFile f = new RandomAccessFile(installation, "r");
        byte[] bytes = new byte[(int) f.length()];
        f.readFully(bytes);
        f.close();
        return new String(bytes);
    }

    private static void writeInstallationFile(File installation) throws IOException {
        FileOutputStream out = new FileOutputStream(installation);
        String id = UUID.randomUUID().toString();
        out.write(id.getBytes());
        out.close();
    }


//    public static void getUserInfo(final SuccessCallBack successCallBack) {
//        if (TextUtils.isEmpty(getUid())) {
//            return;
//        }
//        OkHttpUtils.get()
//                .addHeader("from", "android")
//                .addHeader("token", SharedPreferenceUtil.getString(BaseApp.getApp(), Constant.TOKEN, ""))
//                .addHeader("uid", getUid())
//                .url(NetConstant.USER_INFO)
//                .build()
//                .execute(new MyStringCallback() {
//                    @Override
//                    public void onError(Call call, Exception e, int id) {
//                    }
//
//                    @Override
//                    public void onResponse(String response, int id) {
//                        LogUtils.d("author" + response);
//                        try {
//                            if (code == 200) {
//                                UserPhonePOJO userPhonePOJO = GsonUtil.buildGson().fromJson(response, UserPhonePOJO.class);
//                                if (userPhonePOJO != null) {
//                                    setUserPhonePOJO(userPhonePOJO);
//
//                                    if (successCallBack != null) {
//                                        successCallBack.successcallback();
//                                    }
//
//                                }
//                            }
//                        } catch (JsonSyntaxException e) {
//                            e.printStackTrace();
//                            Log.d("sss", "error: " + e.getMessage());
//                        }
//
//                    }
//                });
//    }

}
